import {Button, Form, Input, message, Popconfirm, Select, Switch, Table} from "antd";
import React, {useEffect, useState, useTransition} from "react";
import {ColumnsType} from "antd/es/table";
import {LiteratureDataType, MetaType} from "../../util/publicType";
import {useNavigate, useParams} from "react-router-dom";
import {
    delLiterature,
    literatureList,
    literatureUpdateGrounding,
    literatureUpdateRecommend
} from "../../api";
import {AxiosResponse} from "axios";
import {CheckOutlined, CloseOutlined} from '@ant-design/icons';
import {setNullData} from "../../util";
import ReadFile from "../../components/ReadFile";
import RequestLoading from "../../components/RequestLoading";

// 所有文献页面，变化的只有id也就是数据不同
const Literature = () => {
    // 搜索表单
    const [searchForm] = Form.useForm();
    // 数据
    const [data, setData] = useState<LiteratureDataType[]>([]);
    // 分页
    const [page, setPage] = useState<number>(1);
    // 当前页数
    const [size, setSize] = useState<number>(15);
    // 名字搜索
    const [name, setName] = useState<string | null>(null);
    // 上架筛选
    const [grounding, setGrounding] = useState<number | null>(null);
    //文件是否查阅
    const [isMolFile, setIsMolFile] = useState<boolean>(false);
    // 当前行数据
    const [currentData, setCurrentData] = useState<LiteratureDataType | null>(null);
    // 过渡
    const [loading, startTransition] = useTransition();
    //音频还是视频
    const [isShow, setIsShow] = useState<{ isVideo: boolean, isAudio: boolean }>({
        isVideo: false,
        isAudio: false
    });

    // 字典id
    const [dictId, setDictId] = useState<string>("");

    // 分页数据
    const [meta, setMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });

    // 地址
    const n = useNavigate();
    // 拿到当前分类id参数
    const {id} = useParams();

    // 请求
    const getData = (page: number, size: number, name: string | null = null, grounding: number | null = null) => {
        startTransition(() => {
            literatureList(page, size, name, grounding, id as string).then((r: AxiosResponse) => {
                let {data, meta, type_id} = r.data.data;
                data = data.map((v: LiteratureDataType) => {
                    return {
                        ...v,
                        cover_url: v.cover.path,
                        file_url: v.file.path,
                        key: v.id,
                        author: setNullData(v.author),
                        press: setNullData(v.press),
                        code: setNullData(v.code)
                    }
                });
                setData(data);
                setDictId(type_id);
                setMeta(meta);
            }, err => message.error(err))
        });
    }

    // 当文献类型变化时监听执行
    useEffect(() => {
        setPage(1);
        setSize(15);
        setName(null);
        setGrounding(null);
        // 重新请求
        getData(page, size);
        // 清除搜索条件
        searchForm.resetFields();
    }, [id]);

    // 表头
    const columns: ColumnsType<LiteratureDataType> = [
        {
            title: "封面",
            dataIndex: "cover_url",
            key: "cover_url",
            align: "center",
            render: (v: string) => {
                return (
                    <div style={{width: "50px", height: "50px", margin: "0 auto"}}>
                        <img src={v} width={50} height={50} alt="" style={{objectFit: "contain"}}/>
                    </div>
                )
            }
        },
        {
            title: "文献名字",
            dataIndex: "name",
            key: "name",
            align: "center",
            width: "18%"
        },
        {
            title: "作者",
            dataIndex: "author",
            key: "author",
            align: "center"
        },
        {
            title: "出版社",
            dataIndex: "press",
            key: "press",
            align: "center"
        },
        {
            title: "文件类型",
            dataIndex: "file_url",
            key: "file_url",
            align: "center",
            render: (v: string) => {
                return (
                    <div>{v.substring(v.lastIndexOf(".") + 1)}</div>
                )
            }
        },
        {
            title: "阅读数",
            dataIndex: "visit_num",
            key: "visit_num",
            align: "center"
        },
        {
            title: "是否推荐",
            dataIndex: "recommend",
            key: "recommend",
            align: "center",
            render: (v: number, record: LiteratureDataType) => {
                return (
                    <Switch
                        checkedChildren={<CheckOutlined/>}
                        unCheckedChildren={<CloseOutlined/>}
                        defaultChecked={!!v}
                        onChange={(v: boolean) => {
                            literatureUpdateRecommend(record.id, {recommend: v ? 1 : 0}).then(async () => {
                                getData(page, size, name, grounding);
                                await message.success(v ? "已推荐到首页" : "已取消推荐");
                            }, err => message.error(err))
                        }}
                    />
                )
            }
        },
        {
            title: "是否上架",
            dataIndex: "grounding",
            key: "grounding",
            align: "center",
            render: (v: number, record: LiteratureDataType) => {
                return (
                    <Switch
                        checkedChildren={<CheckOutlined/>}
                        unCheckedChildren={<CloseOutlined/>}
                        defaultChecked={!!v}
                        onChange={(v: boolean) => {
                            literatureUpdateGrounding(record.id, {grounding: v ? 1 : 0}).then(async () => {
                                getData(page, size, name, grounding);
                                await message.success(v ? "已上架" : "已取消上架");

                            }, err => message.error(err))
                        }}
                    />
                )
            }
        },
        {
            title: "文献编号",
            dataIndex: "code",
            key: "code",
            align: "center"
        },
        {
            title: "操作",
            dataIndex: "id",
            key: "id",
            align: "center",
            render: (v: string, record: LiteratureDataType) => {
                return (
                    <div>
                        <Button type="primary" onClick={() => editClick(v)}
                                style={{marginRight: "10px"}}>编辑</Button>
                        <Popconfirm
                            title="删除操作"
                            description={`确定删除${record.name}文献吗？`}
                            onConfirm={() => delClick(v)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger>删除</Button>
                        </Popconfirm>
                        <Button type="primary"
                                onClick={() => seeClick(record)}
                                style={{marginLeft: "10px"}}>查阅</Button>
                    </div>
                )
            }
        }
    ]

    // 查看
    const seeClick = (v: LiteratureDataType) => {
        // 保存数据
        setCurrentData(v);
        const type = v.file_url.substring(v.file_url.lastIndexOf(".") + 1);
        switch (type) {
            case "pdf":
                setIsMolFile(false);
                return window.open(v.file_url);
            case "mp3":
                setIsMolFile(true);
                return setIsShow({
                    isAudio: true,
                    isVideo: false
                })
            case "mp4":
                setIsMolFile(true);
                return setIsShow({
                    isAudio: false,
                    isVideo: true
                });
            default:
                setIsMolFile(false);
                return setIsShow({
                    isAudio: false,
                    isVideo: false
                });
        }
    }
    // 搜索条件
    const searchFinish = (v: { name: string, grounding: number }) => {
        if (!v.name) {
            setName(null)
        } else {
            setName(v.name)
        }
        if (!v.grounding) {
            setGrounding(null)
        } else {
            setGrounding(v.grounding)
        }
        getData(page, size, v.name, v.grounding);
    }
    // 添加
    const addClick = () => {
        n(`/literature/create/${dictId}`);
    }

    // 编辑
    const editClick = (id: string) => {
        n(`/literature/update/${id}`);
    }

    // 删除
    const delClick = (id: string) => {
        delLiterature(id).then(async () => {
            getData(page, size, name, grounding);
            await message.success("删除成功")
        })
    }

    return (
        <>
            <div style={{padding: "30px 0"}}>
                <Form form={searchForm} layout="inline" onFinish={searchFinish}>
                    <Form.Item
                        name="name"
                        label="文献名字"
                    >
                        <Input placeholder="请输入分类名字"/>
                    </Form.Item>
                    <Form.Item
                        name="grounding"
                        label="上架状态"
                    >
                        <Select
                            style={{width: "200px"}}
                            placeholder="请选择分类"
                            options={[
                                {
                                    label: "未上架",
                                    value: "0",
                                },
                                {
                                    label: "已上架",
                                    value: "1"
                                }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" style={{marginRight: "10px"}} htmlType="submit">
                            搜索
                        </Button>
                        <Button type="primary" htmlType="reset" style={{marginRight: "10px"}}>
                            重置
                        </Button>
                        <Button type="primary" onClick={addClick}>
                            新建
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {
                loading ? (<RequestLoading/>) :
                    (
                        <Table columns={columns} dataSource={data} pagination={
                            {
                                current: meta.currentPage,
                                defaultCurrent: meta.currentPage,
                                defaultPageSize: meta.perSize,
                                pageSize: meta.perSize,
                                showQuickJumper: true,
                                showSizeChanger: true,
                                showTotal: (t: number) => `总条数${t}`,
                                total: meta.total,
                                onChange: (page: number, perSize: number) => {
                                    setPage(page)
                                    setSize(perSize);
                                    getData(page, perSize, name, grounding);
                                }
                            }
                        }/>
                    )
            }


            {/*预览*/}
            <ReadFile isMolFile={isMolFile}
                      setIsMolFile={setIsMolFile}
                      isShow={isShow}
                      url={currentData?.file?.path ?? ''}/>
        </>
    )
}

export default Literature;